<template>
    <div class="container">
        
            <h1>服务器监控</h1>
            <!-- 图表容器 -->
            <div id="chart" class="chart"></div>
            <!-- 警告提示 -->
            <div v-if="warnings.length > 0" class="warnings">
                <h2>警告信息</h2>
                <ul>
                    <li v-for="(warning, index) in warnings" :key="index">
                        {{ warning }}
                    </li>
                </ul>
            </div>
        
    </div>
</template>

<script setup>
import * as echarts from "echarts";
import { ref, onMounted, onBeforeUnmount } from "vue";

const servers = ref([]);
const warnings = ref([]); // 用于存储超出阈值的警告信息
let socket = null;
let intervalId = null;
let chart = null;

// 初始化 ECharts 图表
const initChart = () => {
    const chartDom = document.getElementById("chart");
    chart = echarts.init(chartDom);

    const option = {
       
        tooltip: {
            trigger: "axis",
        },
        legend: {
            data: ["CPU 占用率 (%)", "温度 (°C)"],
            bottom: 0,
            textStyle: {
                fontSize: 12,
            },
        },
        grid: {
            left: "10%",
            right: "10%",
            bottom: "15%",
            top: "15%",
        },
        xAxis: {
            type: "category",
            data: [],
            axisLabel: {
                rotate: 30,
                interval: 0,
                fontSize: 12,
            },
        },
        yAxis: [
            {
                type: "value",
                name: "CPU 占用率 (%)",
                min: 0,
                max: 100,
                position: "left",
                axisLabel: {
                    formatter: "{value}%",
                    fontSize: 12,
                },
            },
            {
                type: "value",
                name: "温度 (°C)",
                min: 0,
                max: 100,
                position: "right",
                axisLabel: {
                    formatter: "{value}°C",
                    fontSize: 12,
                },
            },
        ],
        series: [
            {
                name: "CPU 占用率 (%)",
                type: "bar",
                data: [],
                yAxisIndex: 0,
                label: {
                    show: true,
                    position: "top", // 显示在柱状图上方
                    formatter: "{c}%", // 显示数值并加上单位
                    fontSize: 10,
                },
                barWidth: "30%",
            },
            {
                name: "温度 (°C)",
                type: "bar",
                data: [],
                yAxisIndex: 1,
                label: {
                    show: true,
                    position: "top", // 显示在柱状图上方
                    formatter: "{c}°C", // 显示数值并加上单位
                    fontSize: 10,
                },
                barWidth: "30%",
            },
        ],
    };

    chart.setOption(option);
};

// 更新图表数据
const updateChart = () => {
    if (!chart || servers.value.length === 0) return;

    const names = servers.value.map((server) => server.name);
    const cpuData = servers.value.map((server) =>
        parseFloat(server.cpu_usage.replace("%", "")) || 0
    );
    const tempData = servers.value.map((server) => server.temperature || 0);

    chart.setOption({
        xAxis: {
            data: names,
        },
        series: [
            {
                name: "CPU 占用率 (%)",
                data: cpuData,
            },
            {
                name: "温度 (°C)",
                data: tempData,
            },
        ],
    });

    // 检测是否有超出阈值的数据
    warnings.value = [];
    servers.value.forEach((server) => {
        const cpuUsage = parseFloat(server.cpu_usage.replace("%", "")) || 0;
        const temperature = server.temperature || 0;

        if (cpuUsage > 80) {
            warnings.value.push(
                `服务器 ${server.name} 的 CPU 占用率超出阈值 (${cpuUsage}%)！`
            );
        }
        if (temperature > 60) {
            warnings.value.push(
                `服务器 ${server.name} 的温度超出阈值 (${temperature}°C)！`
            );
        }
    });
};

// 初始化 WebSocket
const initWebSocket = () => {
    socket = new WebSocket("ws://localhost:8000/ws/monitor/");

    socket.onopen = () => {
        console.log("WebSocket 连接成功");

        // 定时发送请求
        intervalId = setInterval(() => {
            socket.send(JSON.stringify({ action: "fetch_status" }));
        }, 2000); // 每隔 2 秒发送一次请求
    };

    socket.onmessage = (event) => {
        servers.value = JSON.parse(event.data);
        console.log("服务器数据更新:", servers.value);
        updateChart(); // 更新图表数据
    };

    socket.onerror = (error) => {
        console.error("WebSocket 错误:", error);
    };

    socket.onclose = () => {
        console.log("WebSocket 连接已关闭");
        clearInterval(intervalId);
    };
};

onMounted(() => {
    initWebSocket();
    initChart();
});

onBeforeUnmount(() => {
    if (socket) {
        socket.close();
    }
    clearInterval(intervalId);
});
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    transform: translate(-50%);
    left: 50%;
    position: relative;
    width: 350px;
    height: 600px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    padding: 10px;
    box-sizing: border-box;
    background-color: #f8f9fa;
    font-family: Arial, sans-serif;
}

h1 {
    font-size: 18px;
    margin-bottom: 10px;
    text-align: center;
    color: #333;
}

.chart {
    width: 100%;
    /* 确保图表宽度适配容器 */
    height: 250px;
    /* 调整图表高度以适应容器 */
    background-color: #ffffff;
    border: 1px solid #ddd;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    /* 防止图表溢出容器 */
    box-sizing: border-box;
}

.warnings {
    width: 100%;
    padding: 10px;
    background-color: #fff3f3;
    border: 1px solid #f5c6cb;
    border-radius: 8px;
    color: #721c24;
    font-size: 14px;
    box-sizing: border-box;
}

.warnings h2 {
    font-size: 16px;
    margin-bottom: 5px;
}

.warnings ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.warnings li {
    margin: 5px 0;
    font-size: 14px;
}
</style>
